"use client"

import { useRef, useState, useEffect } from 'react'
import { textStyles } from '../lib/fontConfig'

interface WritingCanvasProps {
  referenceCharacter: string
  strokeCount: number
  onWritingComplete?: (strokes: number) => void
}

export function WritingCanvas({ 
  referenceCharacter, 
  strokeCount, 
  onWritingComplete 
}: WritingCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [isDrawing, setIsDrawing] = useState(false)
  const [currentStrokes, setCurrentStrokes] = useState(0)
  const [lastPoint, setLastPoint] = useState<{ x: number; y: number } | null>(null)

  // 初始化画布
  useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    // 设置画布尺寸
    const rect = canvas.getBoundingClientRect()
    canvas.width = rect.width * window.devicePixelRatio
    canvas.height = rect.height * window.devicePixelRatio
    ctx.scale(window.devicePixelRatio, window.devicePixelRatio)

    // 设置绘图样式
    ctx.lineCap = 'round'
    ctx.lineJoin = 'round'
    ctx.strokeStyle = '#2563eb'
    ctx.lineWidth = 3

    // 绘制田字格
    drawGrid(ctx, rect.width, rect.height)
  }, [])

  // 绘制田字格辅助线
  const drawGrid = (ctx: CanvasRenderingContext2D, width: number, height: number) => {
    ctx.save()
    ctx.strokeStyle = '#e5e7eb'
    ctx.lineWidth = 1
    ctx.setLineDash([5, 5])

    // 外框
    ctx.strokeRect(0, 0, width, height)
    
    // 中心十字线
    ctx.beginPath()
    ctx.moveTo(width / 2, 0)
    ctx.lineTo(width / 2, height)
    ctx.moveTo(0, height / 2)
    ctx.lineTo(width, height / 2)
    ctx.stroke()

    // 对角线（淡一些）
    ctx.strokeStyle = '#f3f4f6'
    ctx.beginPath()
    ctx.moveTo(0, 0)
    ctx.lineTo(width, height)
    ctx.moveTo(width, 0)
    ctx.lineTo(0, height)
    ctx.stroke()

    ctx.restore()
  }

  // 获取鼠标/触摸位置
  const getEventPos = (e: React.MouseEvent | React.TouchEvent) => {
    const canvas = canvasRef.current
    if (!canvas) return { x: 0, y: 0 }

    const rect = canvas.getBoundingClientRect()
    const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX
    const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY

    return {
      x: clientX - rect.left,
      y: clientY - rect.top
    }
  }

  // 开始绘制
  const startDrawing = (e: React.MouseEvent | React.TouchEvent) => {
    e.preventDefault()
    setIsDrawing(true)
    const pos = getEventPos(e)
    setLastPoint(pos)
    
    // 增加笔画计数
    setCurrentStrokes(prev => prev + 1)
  }

  // 绘制过程
  const draw = (e: React.MouseEvent | React.TouchEvent) => {
    e.preventDefault()
    if (!isDrawing || !lastPoint) return

    const canvas = canvasRef.current
    const ctx = canvas?.getContext('2d')
    if (!canvas || !ctx) return

    const currentPos = getEventPos(e)

    ctx.beginPath()
    ctx.moveTo(lastPoint.x, lastPoint.y)
    ctx.lineTo(currentPos.x, currentPos.y)
    ctx.stroke()

    setLastPoint(currentPos)
  }

  // 结束绘制
  const stopDrawing = () => {
    setIsDrawing(false)
    setLastPoint(null)
    
    // 检查是否完成书写
    if (currentStrokes >= strokeCount && onWritingComplete) {
      onWritingComplete(currentStrokes)
    }
  }

  // 清除画布
  const clearCanvas = () => {
    const canvas = canvasRef.current
    const ctx = canvas?.getContext('2d')
    if (!canvas || !ctx) return

    ctx.clearRect(0, 0, canvas.width, canvas.height)
    
    // 重新绘制田字格
    const rect = canvas.getBoundingClientRect()
    drawGrid(ctx, rect.width, rect.height)
    
    setCurrentStrokes(0)
  }

  // 撤销上一笔画（简化实现）
  const undoLastStroke = () => {
    if (currentStrokes > 0) {
      setCurrentStrokes(prev => prev - 1)
      // 这里可以实现更复杂的撤销逻辑
    }
  }

  return (
    <div className="w-full h-full flex flex-col">
      {/* 画布区域 */}
      <div className="flex-1 relative bg-white rounded-lg border-2 border-gray-200 overflow-hidden">
        <canvas
          ref={canvasRef}
          className="w-full h-full cursor-crosshair"
          onMouseDown={startDrawing}
          onMouseMove={draw}
          onMouseUp={stopDrawing}
          onMouseLeave={stopDrawing}
          onTouchStart={startDrawing}
          onTouchMove={draw}
          onTouchEnd={stopDrawing}
        />
        
        {/* 参考字水印 */}
        <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
          <div 
            className="text-gray-200 select-none"
            style={{ fontSize: '120px', fontWeight: 'bold' }}
          >
            {referenceCharacter}
          </div>
        </div>

        {/* 笔画计数器 */}
        <div className="absolute top-2 left-2 bg-blue-500 text-white px-2 py-1 rounded-full text-xs">
          {currentStrokes}/{strokeCount} 画
        </div>

        {/* 完成提示 */}
        {currentStrokes >= strokeCount && (
          <div className="absolute top-2 right-2 bg-green-500 text-white px-3 py-1 rounded-full text-xs animate-bounce">
            ✓ 完成！
          </div>
        )}
      </div>

      {/* 控制按钮 */}
      <div className="flex justify-center space-x-2 mt-3">
        <button
          onClick={clearCanvas}
          className={`${textStyles.secondaryButton} px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 hover:scale-105 transition-all duration-300`}
        >
          🗑️ 清除
        </button>
        
        <button
          onClick={undoLastStroke}
          disabled={currentStrokes === 0}
          className={`
            ${textStyles.secondaryButton} px-4 py-2 rounded-lg transition-all duration-300
            ${currentStrokes === 0 
              ? 'bg-gray-300 text-gray-500 cursor-not-allowed' 
              : 'bg-orange-500 text-white hover:bg-orange-600 hover:scale-105'
            }
          `}
        >
          ↶ 撤销
        </button>

        <button
          onClick={() => {
            // 可以添加保存功能
            const canvas = canvasRef.current
            if (canvas) {
              const dataURL = canvas.toDataURL('image/png')
              console.log('保存的图片数据:', dataURL)
              // 这里可以实现保存到本地存储或上传
            }
          }}
          className={`${textStyles.secondaryButton} px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 hover:scale-105 transition-all duration-300`}
        >
          💾 保存
        </button>
      </div>

      {/* 书写提示 */}
      <div className="text-center mt-2">
        <div className={`${textStyles.caption} text-gray-600`}>
          {currentStrokes === 0 
            ? '在画布上练习书写，参考背景中的字形'
            : currentStrokes < strokeCount
              ? `继续书写，还需要 ${strokeCount - currentStrokes} 画`
              : '书写完成！可以清除后重新练习'
          }
        </div>
      </div>
    </div>
  )
} 